How to get correct children ids using fields_for "parents[]", parent do |f| using f.fields_for :children, child ?

Posted by Anatortoise House on Stack Overflow See other posts from Stack Overflow or by Anatortoise House
Published on 2011-06-24T23:56:11Z Indexed on 2011/06/25 0:23 UTC
Read the original article Hit count: 145

Filed under:
|

I'm editing multiple instances of a parent model in an index view in one form, as in Railscasts #198. Each parent has_many :children and accepts_nested_attributes_for :children, as in Railscasts #196 and #197

<%= form_tag %>
  <% for parent in @parents %>
    <%= fields_for "parents[]", parent do |f|
      <%= f.text_field :job %>
      <%= f.fields_for :children do |cf| %>
         <% cf.text_field :chore %>
      <% end %> 
    <% end %> 
  <% end %> 
<% end %>  

Given parent.id==1
f.text_field :job correctly generates

<input id="parents_1_job" type="text" value="coding" size="30" name="parents[1][job]">  

But cf.text_field :chore generates ids and names that don't have the parent index.

id="parents_children_attributes_0_chore"  
name="parents[children_attributes][0][chore]"    

If I try passing the specific child object to f.fields_for like this:

<% for child in parent.children %>
  <%= f.fields_for :children, child do |cf| %>
    <%= cf.text_field :chore %>
  <% end %>
<% end %>  

I get the same. If I change the method from :children to "[]children" I get

id="parents_1___children_chore"

which gets the right parent_index but doesn't provide an array slot for the child index.

"[]children[]" isn't right either: id="parents_1__children_3_chore"

as I was expecting attributes_0_chore instead of 3_chore.

Do I need to directly modify an attribute of the FormBuilder object, or subclass FormBuilder to make this work, or is there a syntax that fits this situation?

Thanks for any thoughts.

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about fields-for